﻿using Inovout.Component;
using Inovout.Runtime;
using MvcSiteMapProvider;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Inovout.Web.Mvc.Security
{
    public static class ResourceProvider
    {
        private static UrlHelper urlHelper = new UrlHelper();
        static ResourceProvider()
        {
            
        }

        /// <summary>
        /// 同步MVC.SITE中的内容
        /// </summary>
        public static void SyncResource()
        {
            //获取资源
            var node = BuildSiteMap(SiteMaps.Current.RootNode);
            var json = JsonConvert.SerializeObject(node);

            //发送资源到服务器
            SendResource(json);
        }


        private static object BuildSiteMap(ISiteMapNode node)
        {
            var uri = HttpContext.Current.Request.Url;
           // urlHelper.Action(node.Action,node.Controller);
           // new Uri(HttpContext.Current.Request.Url, urlHelper.Action(node.Action, node.Controller));
            return new { title = node.Title, url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, node.Url), method = node.HttpMethod, children = node.ChildNodes.Select(c => BuildSiteMap(c)) };
        }


        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="resourceJson"></param>
        private static void SendResource(string resourceJson)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
            string syncUrl = ComponentRegistry.Resolve<IApplication>().Properties["client.sync"];

            List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
            paramList.Add(new KeyValuePair<string, string>("resource", resourceJson));
            HttpResponseMessage response = httpClient.PostAsync(new Uri(syncUrl), new FormUrlEncodedContent(paramList)).Result;

            String result = response.Content.ReadAsStringAsync().Result;

        }



    }

   
}
